package org.zhaya.sdk.swamill;


import cn.hutool.core.util.IdUtil;
import io.logz.sawmill.ConditionFactoryRegistry;
import io.logz.sawmill.ExecutionStep;
import io.logz.sawmill.Pipeline;
import io.logz.sawmill.ProcessorFactoryRegistry;
import io.logz.sawmill.parser.ExecutionStepsParser;
import io.logz.sawmill.parser.PipelineDefinition;
import lombok.Getter;
import org.apache.commons.lang3.StringUtils;

import java.util.List;
import java.util.Optional;

public class CustomPipeline extends Pipeline {

    @Getter
    private String name;

    public CustomPipeline(String id, String name, List<ExecutionStep> executionSteps, boolean stopOnFailure) {
        super(id, executionSteps, stopOnFailure);
        this.name = name;
    }

    public static final class Factory {
        private final ExecutionStepsParser executionStepsParser;

        public Factory(ProcessorFactoryRegistry processorFactoryRegistry, ConditionFactoryRegistry conditionFactoryRegistry) {
            this.executionStepsParser = new ExecutionStepsParser(processorFactoryRegistry, conditionFactoryRegistry);
        }

        public CustomPipeline create(String config) {
            return this.create(null, null, config);
        }

        public CustomPipeline create(String id, String config) {
            return this.create(id, null, config);
        }

        public CustomPipeline create(String id, String name, String config) {
            PipelineDefinition pipelineDefinition = CustomPipelineDefinitionJsonParser.parse(config);
            return this.create(StringUtils.defaultIfBlank(id, IdUtil.fastUUID()), name, pipelineDefinition);
        }

        public CustomPipeline create(String id, String name, PipelineDefinition pipelineDefinition) {
            List<ExecutionStep> executionSteps = this.executionStepsParser.parse(pipelineDefinition.getExecutionSteps());
            Optional<Boolean> stopOnFailureNullable = pipelineDefinition.isStopOnFailure();
            boolean stopOnFailure = stopOnFailureNullable.orElse(false);
            return new CustomPipeline(id, name, executionSteps, stopOnFailure);
        }
    }
}
